#define _CRT_SECURE_NO_WARNINGS 1
#include "stack.h"

void InitStack(Stack* head)
{
	head->a = (DataType*)malloc(sizeof(DataType) * 4);
	if (head->a == NULL)
	{
		perror("malloc error!");
		exit(-1);
	}
	head->pos = 0;
	head->capacity = 4;
}

void StackCheck(Stack* head)
{
	if (head->capacity == head->pos)
	{
		DataType* tmp = (DataType*)realloc(head->a, head->capacity * 2 * sizeof(DataType));
		if (tmp == NULL)
		{
			perror("realloc error!");
			exit(-1);
		}
		head->a = tmp;
		head->capacity *= 2;
	}
}

void StackPushBack(Stack* head, int x)
{
	assert(head);
	StackCheck(head);
	head->a[head->pos] = x;
	head->pos++;
}

DataType StackPopBack(Stack* head)
{
	assert(head);
	assert(head->pos > 0);
	int tmp = head->a[head->pos-1];
	head->pos--;
	return tmp;
}

bool IsEmpty(Stack* head)
{
	assert(head);
	if (head->pos)
		return true;
	else
		return false;
}

void StackPrintf(Stack* head)
{
	assert(head);
	int i = head->pos;
	while (i--)
	{
		int x = StackPopBack(head);
		printf("%d ", x);
	}
}

void StackDestory(Stack* head)
{
	free(head->a);
	head->capacity = 0;
	head->pos = 0;
}